package cn.yikaojiuguo.student.ui.usercenter;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.yikaojiuguo.student.R;
import cn.yikaojiuguo.student.app.YiKaoApplication;
import cn.yikaojiuguo.student.support.simple.SimpleTextWatcher;
import cn.yikaojiuguo.student.support.simple.UrlConstants;
import cn.yikaojiuguo.student.support.utils.MD5Util;
import cn.yikaojiuguo.student.support.utils.RequestUtil;
import cn.yikaojiuguo.student.support.utils.ToastUtil;
import cn.yikaojiuguo.student.support.utils.Util;
import cn.yikaojiuguo.student.support.volley.Response;
import cn.yikaojiuguo.student.ui.base.CustomerActionBarActivity;

public class RetrievePasswordActivity extends CustomerActionBarActivity implements View
        .OnClickListener {

    @Bind(R.id.et_number)
    EditText mEt_number;
    @Bind(R.id.et_password)
    EditText mEt_password;
    @Bind(R.id.et_code)
    EditText mEt_code;
    @Bind(R.id.btn_code)
    Button mBtn_code;
    @Bind(R.id.btn_commit)
    Button mBtn_commit;
    //手机号码是否合法的标记位
    private boolean isNumberRight = false;
    //密码是否合法的标记位
    private boolean isPasswordRight = false;
    //验证码是否合法的标记位
    private boolean isCodeRight = false;
    private TimeCount timeCount;
    private String mCode = "1111";

    public static Intent newIntent() {
        Intent intent = new Intent(YiKaoApplication.getInstance(), RetrievePasswordActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrieve_password);
        ButterKnife.bind(this);
        initEvents();
    }

    private void initEvents() {
        setCustomerBackOnclickListener(this);
        timeCount = new TimeCount(60000, 1000);
        mBtn_code.setOnClickListener(this);
        mBtn_code.setClickable(false);
        mBtn_commit.setOnClickListener(this);
        mBtn_commit.setClickable(false);
        //只有当手机号正确，密码大于6位时，才可获取验证码
        mEt_number.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    if (Util.isMoblie(s.toString())) {
                        isNumberRight = true;
                    } else {
                        isNumberRight = false;
                        ToastUtil.showToast(RetrievePasswordActivity.this, "请输入正确的手机号码！");
                    }
                } else {
                    isNumberRight = false;
                }
                setBtnCodeEnable();
                setBtnCommitEnable();
            }
        });
        mEt_password.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= 6) {
                    isPasswordRight = true;
                } else {
                    isPasswordRight = false;
                }
                setBtnCodeEnable();
                setBtnCommitEnable();
            }
        });
        mEt_code.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 4 && s.toString().equals(mCode)) {//验证码正确
                    isCodeRight = true;
                } else if (s.length() == 4 && !s.toString().equals(mCode)) {//验证码不正确
                    isCodeRight = false;
                    ToastUtil.showToast(RetrievePasswordActivity.this, "请输入正确的验证码！");
                } else {
                    isCodeRight = false;
                }
                setBtnCommitEnable();
            }
        });
    }

    private void setBtnCommitEnable() {
        if (isPasswordRight && isNumberRight && isCodeRight) {
            mBtn_commit.setClickable(true);
            mBtn_commit.setBackgroundDrawable(getResources().getDrawable(R.drawable
                    .selector_background_retrieve_btn));
        } else {
            mBtn_commit.setClickable(false);
            mBtn_commit.setBackgroundDrawable(getResources().getDrawable(R.drawable
                    .shape_background_retrieve_btn_unable));
        }
    }

    private void setBtnCodeEnable() {
        if (isPasswordRight && isNumberRight) {
            mBtn_code.setClickable(true);
            mBtn_code.setBackgroundDrawable(getResources().getDrawable(R.drawable
                    .selector_background_retrieve_btn));
        } else {
            mBtn_code.setClickable(false);
            mBtn_code.setBackgroundDrawable(getResources().getDrawable(R.drawable
                    .shape_background_retrieve_btn_unable));
        }
    }

    @Override
    public void onClick(View v) {
        String requestUrl = "";
        switch (v.getId()) {
            case R.id.btn_code:
                showProgressDialog();
                requestUrl = UrlConstants.SEND_CODE + "&mobile=" + mEt_number.getText()
                        .toString().trim() + "&etype=" + 2;
                RequestUtil.requestGet(requestUrl, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        dismissProgressDialog();
                        if (response != null && response.optBoolean("success")) {//成功获取验证码
                            //开始计时
                            timeCount.start();
                            //获取验证码按钮不可点击
                            mBtn_code.setClickable(false);
                            //为验证码赋值
                            mCode = response.optString("message");
                        } else if (response != null && !response.optBoolean("success")) {//获取验证码失败
                            isNumberRight = false;
                            setBtnCodeEnable();
                        }
                    }
                }, null, mTag);
                break;
            case R.id.btn_commit:
                showProgressDialogNotCancel();
                requestUrl = UrlConstants.FIND_PWD + "&mobile=" + YiKaoApplication
                        .getMobileNubmer() + "&pwd=" + MD5Util.encode(mEt_password.getText()
                        .toString().trim()) + "&code=" + mCode;
                RequestUtil.requestGet(requestUrl, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        dismissProgressDialog();
                        if(response!=null && response.optBoolean("success")) {//修改成功
                            ToastUtil.showToast(RetrievePasswordActivity.this,"密码修改成功！");
                            startActivity(PassWordInputActivity.newIntent());
                            finish();
                            leftEnter();
                        }
                    }
                },null,mTag);
                ToastUtil.showToast(this, "commit");
                break;
            case R.id.iv_back:
                startActivity(PassWordInputActivity.newIntent());
                finish();
                leftEnter();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timeCount.cancel();
    }

    class TimeCount extends CountDownTimer {

        /**
         * @param millisInFuture    总时长
         * @param countDownInterval 时间间隔
         */
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mBtn_code.setText((int) millisUntilFinished / 1000 + "");
        }

        @Override
        public void onFinish() {
            //获取验证码按钮可点击
            mBtn_code.setClickable(true);
            mBtn_code.setText(getResources().getString(R.string.activity_retrieve_btn_hint));
        }
    }

    @Override
    public void onBackPressed() {
        mIv_back.performClick();
    }
}
